<?php


namespace App\Jobs;

use App\Models\PartCompany;
use App\Models\RefreshLog;
use App\Services\BookTitleService;
use App\Services\CommonService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class UpdatePaperBtCount implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $redisKey;

    public function __construct($redisKey)
    {
        $this->redisKey = $redisKey;
    }

    public function handle()
    {
        $nowTime = now()->toTimeString();
        if ($nowTime > '01:00:00' && $nowTime < '07:00:00') { //该任务只在 1 点到早上 7 点之间进行  ->whereNotIn('id', [28, 117])
            $partCompany = PartCompany::query()->where('need_update_statistic', 1)->first();
            if ($partCompany) {
                $updatingKey = $this->redisKey . ':' . $partCompany->id;
                if (!redis()->get($updatingKey)) { //如果参建单位并没有执行更新操作
                    RefreshLog::query()->updateOrCreate(
                        [
                            'part_company_id'  => $partCompany->id,
                            'project_id'       => $partCompany->project_id,
                            'type'             => 1
                        ],
                        [
                            'total_count'      => DB::raw('total_count + 1'),
                            'user_id'          => 1,
                            'pre_refresh_time' => date('Y-m-d H:i')
                        ]
                    );
                    redis()->set($updatingKey, 1); //设置为执行中...
                    $this->updatePaperCount($partCompany->id, $updatingKey); //执行队列-纸质档案统计
                }
            }
        }
    }

    /**
     * 更新纸质版案卷相关数量
     */
    public function updatePaperCount($partCompanyId, $updatingKey)
    {
        $bookTitleCount     = 0;
        $catalogCount       = 0;
        $pageNumCount       = 0;
        $blueprintCount     = 0; //蓝图卷数
        $blueprintPageCount = 0; //蓝图张数
        $pdfCount           = 0; //PDF件数
        $pdfPageCount       = 0; //PDF张数
        $pdfDiskCount       = 0;
        /**
         * 下面获取案卷卷数、总页码、总蓝图
         */
        $baseBtTable = "book_titles_{$partCompanyId}";
        $tables = CommonService::getSubTables($baseBtTable); //获取当前参建单位下的案卷全部的分表
        foreach ($tables as $table) {
            $idInfo             = CommonService::getTableParams($table);
            $partCompanyId      = $idInfo['id1'];
            $projectClassifyId  = $idInfo['id2'];
            $count1             = DB::table($table)->whereNull('deleted_at')->count('id'); //案卷卷数
            $count2             = DB::table("book_catalogs_{$partCompanyId}_{$projectClassifyId}")->whereNull('deleted_at')->count('id'); //卷内数
            $count3             = DB::table($table)->whereNull('deleted_at')->sum('page_num'); //页码总数
            $count4             = DB::table($table)->whereNull('deleted_at')->where('blueprint', '>', 0)->count('id');
            $count5             = DB::table($table)->whereNull('deleted_at')->sum('blueprint');
            $bookTitleCount     += $count1;
            $catalogCount       += $count2;
            $pageNumCount       += $count3;
            $blueprintCount     += $count4; //蓝图总卷数，如果哪个案卷包含蓝图
            $blueprintPageCount += $count5; //蓝图总张数
            $bookTitleIds       = CommonService::getBookTitleInstance($partCompanyId, $projectClassifyId)->pluck('id')->toArray();
            foreach ($bookTitleIds as $bookTitleId) {
                $pdfPageInfo  = BookTitleService::getPdfPageNum($partCompanyId, $projectClassifyId, $bookTitleId); //扫描件件数和页数
                $pdfCount     += $pdfPageInfo['pdf_count'];
                $pdfPageCount += $pdfPageInfo['pdf_page_count'];
            }
        }
        $basePdfTable = "book_catalog_pdfs_{$partCompanyId}"; //当前参建单位所属的PDF表
        $tables = CommonService::getSubTables($basePdfTable);
        foreach ($tables as $table) {
            $idInfo   = CommonService::getTableParams($table);
            $tableExt = "{$idInfo['id1']}_{$idInfo['id2']}";
            $fileSize = DB::table("book_titles_$tableExt as bt")
                ->leftJoin("book_catalogs_$tableExt as bc", 'bt.id', '=', 'bc.book_title_id')
                ->leftJoin("book_catalog_pdfs_$tableExt as pdf", 'bc.id', '=', 'pdf.book_catalog_id')
                ->whereNull('bt.deleted_at')
                ->whereNull('bc.deleted_at')
                ->whereNull('pdf.deleted_at')
                ->sum('pdf.file_size');
            $pdfDiskCount += $fileSize;
        }
        PartCompany::query()->where('id', $partCompanyId)->update([
            'book_title_count'      => $bookTitleCount,//案卷总数
            'catalog_count'         => $catalogCount,//卷内总数
            'page_num_count'        => $pageNumCount,//页码总数
            'blueprint_count'       => $blueprintCount,//蓝图卷数
            'blueprint_page_count'  => $blueprintPageCount,//蓝图张数
            'pdf_count'             => $pdfCount, //PDF件数
            'pdf_page_count'        => $pdfPageCount,//PDF张数
            'pdf_disk_count'        => round($pdfDiskCount / 1024), //占用磁盘 KB 转化为 MB
            'need_update_statistic' => 0, //更新过后标记
        ]);
        redis()->del($updatingKey); //执行完毕，删除标识
    }

}
